contextInfo = new Object(); 
contextInfo['cartProductQtyInitial']='';

	function removeOrder(productId, productName) {
	    //(productName);
	    var answer = confirm("Are you sure you want to remove '" + productName + "' from cart?");

	    if (answer == true) {

	        $.ajax({
	            url: "rest/data/removeorder.php",
	            type: 'GET',
	            data: {
	                productId: productId
	            },
	            success: function (result) {
	                //(order.order[i].productname);	
	                //('callback'+result);
	                var removemsg = "'<font color='#FF0000'>" + productName + "</font>' has been removed from your cart";

	                getShoppingCart(removemsg);
					//(result);
	            }
	        });
	    }
	}
	var setOrderCount = function () {
	    $.ajax({
	        url: "rest/data/ordercount.php",
	        type: 'GET',
	        success: function (result) {
	            document.getElementById('order_count').innerHTML = result.trim();
	        }
	    });
	}


	$(document).ready(function () {
	    setOrderCount();

	});
	
	
	
	

	function getShoppingCart(msg) {
	    /*if(msg==null)
	('msg is null');
	
	else
	('msg is : '+msg);*/

	    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
	        xmlhttp = new XMLHttpRequest();
	    } else { // code for IE6, IE5
	        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	    }
	    xmlhttp.onreadystatechange = function () {
	        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
	            count = 5 - 5;
	            //('count:'+count);

	            setOrderCount();
	            var order = xmlhttp.responseText;
				createCart(order,msg);

	        }

	        setOrderCount();
	    }
	    //(count);
	    xmlhttp.open("GET", "rest/data/shoppingcart.php", true);
	    xmlhttp.send();
	}
	
	function createCart(order,msg){
	            order = JSON.parse(order);
	            count = order.ordercount;
	            //('count'+count);
	            var text = '';
	            //var x=document.getElementById("cart_table").rows[0].cells;
	            if (count > 0) {
	                var table = '<div class="error" style="display:none;color:#F00;text-align:left;padding-left:30px;">Only 1-9 allowed</div>'
					+'<table border="0"  align="center" cellpadding="5" cellspacing="2" width="740" >';

	                if (msg != null) {
	                    table = table + '<tr><td colspan="6">' + msg + '</td></tr>';
	                }
	                table = table + '<tr bgcolor="#66C"><td colspan="7"><h1  align="left">Items in your cart</h1></td></tr>';



	                table = table + '<tr  align="center" bgcolor="#6C3"> <td colspan="2" width="80"><h4>Product</h4></td> <td><h4>Qty.</h4></td> <td><h4>Price</h4></td> <td><h4>Savings</h4></td>  <td><h4>Subtotal</h4></td> <td></td></tr>';

	                var total_quantity = 0;
	                var total_price = 0;
					var delivery='Free';
					var coupon_discount='Not Applied';
					var gift='';
					var grand_total=0;
	                var total_savings = 0;

	                for (i = 0; i < count; i++) {
						var j=0;	
						var attributeString='';
						while(order.cart[i].attributes[j]){ 
						attributeString+='<br>'+order.cart[i].attributes[j].attributeName+' : '+order.cart[i].attributes[j].attributeValue;
						//attributeString+=order.cart[i].attributes[j].attributeName+' : <img src="images/attributes/'+order.cart[i].attributes[j].attributeValue+'.gif"> <br>';
						j++;
						}
	                    	
	                    table = 
						table + 
						'<tr align="center">'+
						'<td colspan="2"  align="left"><table border="0"><tr><td><img  src="images/tshirts/' + order.cart[i].productId + '.jpg" height="70" width="70"></td><td valign="top"><span style="font-size:18px;">' +order.cart[i].productName+ '</span>'+attributeString+'</td></tr></table>';
						if(order.cart[i].isAvailable=='L'){
						table = 
						table + 
						'<div id="lessQty" style="color:#F00;text-align:left;">Only '+order.cart[i].quantity+' item available for this product</div>';
						//document.getElementById('lessQty').fadeIn(400).delay(3000).fadeOut(400); 

						}
						table = 
						table + 
						'</td>' + '<td><input  id="qty'+order.cart[i].productId+'box" type="text" value="' + order.cart[i].quantity+'" disabled="disabled"  size="1" maxlength="1" /><br><a href="#" style="color:#009" title="edit" class="quantity" id="qty'+order.cart[i].productId+'">edit</a></td>' + '<td>' + order.cart[i].discountPrice +  '</td><td>'+(order.cart[i].price-order.cart[i].discountPrice)+'</td>' + '<td>' + order.cart[i].discountPrice * order.cart[i].quantity + '</td>' + '<td><a href="javascript:removeOrder(' + order.cart[i].productId + ',\'' + order.cart[i].productName + '\');"  id="removefromcart"> <img  src="images/remove_cart.png" height="20" width="20" ></a></td>' + '</tr>';
						
						total_quantity = total_quantity * 1 + order.cart[i].quantity * 1;
	                    total_price += order.cart[i].discountPrice * order.cart[i].quantity;
						total_savings+=(order.cart[i].price-order.cart[i].discountPrice)*  order.cart[i].quantity;		
						

	                }
					
					table =
					 table +
					'<tr align="center">' +
					 '<td colspan="3"></td>' 
					 + '<td colspan="2"><input type="checkbox"   name="isGiftWrap" id="isGiftWrap"'; 
					if(order.gift.isGift){					
						table =table +'checked';
						gift=order.gift.amountGiftWrap;
					}
				   
					table =
					 table +

				'>Gift Wrap</td>' + '<td> ' + gift + '  </td><td></td>'  + '</tr>';
					// (table);
					grand_total=total_price;
					if (order.finalPayment.shippingCharge!=0){
						delivery=order.finalPayment.shippingCharge;
//						grand_total=total_price+delivery;						
					}
						
/*					if (gift!=''){
						grand_total=total_price+gift;
					}
*/						
					table =
					 table + 
					 
					'<tr align="center">' +
					 '<td colspan="3"><div id="errorCoupon" style="display:none;color:#F00;text-align:left;">Oops! Seems this is an Invalid coupon </div></td>' + '<td colspan="2">Delivery Charges</td>' + '<td> ' + delivery + '  </td><td></td>'  + '</tr>';
					
					table=table+'<tr align="center">' +
					'<td colspan="3" align="left">';
					//alert(order.coupons.discountApply);
					if(order.coupons.discountApply=='N'||order.coupons.discountApply=='L'){
					table=table+'<div id="beforeCoupon"><input type="text" id="couponCode" value ="Enter Coupon Code" title="Check Coupon"> <span style="background-color:#0099CC;  padding:2px"><a id="applyCoupon" href="#">&nbsp;Apply Coupon&nbsp;</a></span></div>'	;
					}
					else if(order.coupons.discountApply=='Y'){
					coupon_discount=order.coupons.discount;
					table=table+'<div id="afterCoupon"  style="vertical-align:top"><a href="#" id="removeCoupon" ><img src="images/remove_cart.png" height="20" width="20" ></a>'+order.coupons.couponText+'</div>';
					}
					
					table=table+
					'</td>' +
					'<td colspan="2">Coupon Discount</td>' + '<td> ' + coupon_discount + '  </td><td></td>'  + '</tr>';

	                table =
					 table + 
					 '<tr><td colspan="7"><hr></td></tr>' + 
					'<tr align="center">' +
					 '<td>Total Savings</td>' + '<td><h3> Rs. ' + order.finalPayment.savings + ' /- </h3></td>' + '<td></td>' + '<td colspan="2">Grand Total</td>' + '<td><h4> Rs. ' + order.finalPayment.grandTotal + ' /- </h4></td><td></td>'  + '</tr>'+
					    '<tr><td colspan="7"><hr></td></tr>' ;

	               

	                table = table + '<tr align="center"><td align="left"><input type="text" size="10" value ="Enter pincode" title="Check how long does delivery take"> <span style="background-color:#0099CC;  padding:1px"><a href = "#">&nbsp;Check&nbsp;</a></span></td><td align="left"></td><td colspan="2"><a href = "javascript:void(0)" onclick = "document.getElementById(\'light\').style.display=\'none\';document.getElementById(\'fade\').style.display=\'none\'"><h4>Continue shopping</h4></a></td><td ></td><td><a href = "checkout.php" class="wishbtn" >Proceed</a></td><td></td></tr>';
	                table = table + '</table>';



	            }

	            //('count:'+count);

	            if (count > 0)
	                document.getElementById('table_container').innerHTML = table;

	            else {


	                if (msg != null) {
	                    var remove_msg_table = '<table border="0"  align="center" ><tr><td >' + msg + '</td></tr></table>';
	                    //('ater table');
	                }

	                var cart_empty_table

	                = '<br><br><table border="0"  align="center" cellpadding="5" cellspacing="2" width="300">';
	                cart_empty_table = cart_empty_table +

	                '<tr><td><h1  align="center">Your cart is empty</h1></td></tr>' +
	                    '<tr align="center"><td ><a href = "javascript:void(0)" onclick = "document.getElementById(\'light\').style.display=\'none\';document.getElementById(\'fade\').style.display=\'none\'"><h3>Start adding items</h3></a></td></tr>' +
	                    '</table>';
	                //(msg);
	                if (msg != null) {
	                    document.getElementById('table_container').innerHTML = remove_msg_table + cart_empty_table;
	                    //('ater print');

	                } else document.getElementById('table_container').innerHTML = cart_empty_table;

	            }
	        setOrderCount();
			//('hello');
	
	}
	
	$(document).delegate('.quantity','click',function(event){
		var id=$(this).attr('id');
		var boxid=id+'box';
		var cartProductId=id.substring(3);
		var cartProductQty=document.getElementById(boxid).value;
		if(document.getElementById(id).innerHTML=='edit'){
		contextInfo['cartProductQtyInitial']=document.getElementById(boxid).value;
		document.getElementById(boxid).disabled=false;
		document.getElementById(id).innerHTML='save';
		}
		else{
		regex = /^[1-9]+$/;
			if(regex.test(cartProductQty)) {			
				document.getElementById(boxid).disabled=true;
				document.getElementById(id).innerHTML='edit';
				$.ajax({
				url: "rest/data/quantityProductCart.php",
				type: 'GET',
				data: {
					productId: cartProductId,quantity:cartProductQty
				},
				success: function (result) {
				createCart(result);					
				}
				});
			}
			else {
				document.getElementById(boxid).value=contextInfo['cartProductQtyInitial'];
		        $('.error').fadeIn(400).delay(3000).fadeOut(400); //fade out after 3 seconds
			}
		}
			
	});
	
	$(document).delegate('#isGiftWrap','click',function(event){
	var isGiftWrapVar=document.getElementById('isGiftWrap').checked;
	 $.ajax({
		url: "rest/data/giftWrapCart.php",
		type: 'GET',
		 data: {
			isGiftWrap: isGiftWrapVar
		},
		success: function (result) {
		createCart(result);	
						
		}
		});
	});
	
	$(document).delegate('#removeCoupon','click',function(event){
	 $.ajax({
		url: "rest/data/removeCoupons.php",
		type: 'GET',
		 data: {
		},
		success: function (result) {
		createCart(result);	
		document.getElementById('errorCoupon').innerHTML="Coupon discount succesfully removed from cart";
	    $('#errorCoupon').fadeIn(400).delay(3000).fadeOut(400); 						
		}
		});
	});
	
	
	$(document).delegate('#applyCoupon','click',function(event){

		var couponCode=document.getElementById('couponCode').value;
		//alert(couponCode);
		
		 $.ajax({
			url: "rest/data/couponsCart.php",
			type: 'GET',
			 data: {
				couponCode:couponCode
			},
			success: function (result) {
				resultTemp=JSON.parse(result);
//				alert(resultTemp.coupons.discountApply);
				if(resultTemp.coupon=='N'){
	            $('#errorCoupon').fadeIn(400).delay(3000).fadeOut(400); 
				}
				else if (resultTemp.coupons.discountApply=='L'){
//				alert(document.getElementById('errorCoupon').innerHTML);
alert(resultTemp.coupons.minBuy - resultTemp.coupons);
				document.getElementById('errorCoupon').innerHTML="Shop for Rs. "+resultTemp.coupons.minBuy +" "+resultTemp.coupons.amount+" more to avail this coupon"
	            $('#errorCoupon').fadeIn(400).delay(3000).fadeOut(400); 
				}		
				else
				createCart(result);	
			}
		});
	});